package batch

import (
	"fmt"
	
	"mariadb-operator/pkg/apis/finupgroup/v1alpha1"

	batchv1 "k8s.io/api/batch/v1"
	batchv1beta1 "k8s.io/api/batch/v1beta1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// NewCronJob will return a kubernetes cronJob
func NewCronJob(cronbackup *v1alpha1.MariaDBCronBackup) *batchv1beta1.CronJob {
	image, backupCMD := help(cronbackup.Spec.BackupTemplate)
	envs := envs(cronbackup.Spec.BackupTemplate, cronbackup.Spec.BackupTemplate.Cluster, cronbackup.Namespace)
	cb := &batchv1beta1.CronJob{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "batch/v1beta1",
			Kind:       "CronJob",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      cronbackup.Name,
			Namespace: cronbackup.Namespace,
		},
		Spec: batchv1beta1.CronJobSpec{
			Schedule: cronbackup.Spec.Schedule,
			JobTemplate: batchv1beta1.JobTemplateSpec{
				Spec: batchv1.JobSpec{
					Template: corev1.PodTemplateSpec{
						Spec: corev1.PodSpec{
							RestartPolicy: corev1.RestartPolicyOnFailure,
							Volumes: []corev1.Volume{
								corev1.Volume{
									Name: "backup",
									VolumeSource: corev1.VolumeSource{
										EmptyDir: &corev1.EmptyDirVolumeSource{},
									},
								},
							},
							InitContainers: []corev1.Container{
								corev1.Container{
									Name:            fmt.Sprintf("init-%v", cronbackup.Name),
									Image:           image,
									ImagePullPolicy: corev1.PullAlways,
									Command:         []string{"bash", "-c", backupCMD},
									VolumeMounts: []corev1.VolumeMount{
										corev1.VolumeMount{
											Name:      "backup",
											MountPath: "/tmp",
										},
									},
									Env: envs,
								},
							},
							Containers: []corev1.Container{
								corev1.Container{
									Name:            cronbackup.Name,
									Image:           image,
									ImagePullPolicy: corev1.PullAlways,
									Command:         []string{"bash", "-c", "mariadb-backup"},
									VolumeMounts: []corev1.VolumeMount{
										corev1.VolumeMount{
											Name:      "backup",
											MountPath: "/tmp",
										},
									},
									Env: envs,
								},
							},
						},
					},
				},
			},
		},
	}
	return cb
}
